package com.liwy3.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Copyright © 元气森林（北京）食品科技集团有限公司. All rights reserved.
 *
 * @Description:
 * @author: Crazy4J
 * @date: 2022年01月19日 18:20
 * @version: V1.0
 */
public class CompareSet {


    public static final CountDownLatch preinitializationComplete = new CountDownLatch(1);
    public static volatile AtomicBoolean preinitializationStarted = new AtomicBoolean(
            false);
    public static Integer count = 0;

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            Thread thread = new Thread(new Worker());
            thread.start();
        }
        try {
            CompareSet.preinitializationComplete.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("初始化完成");

    }

}

class Worker implements Runnable {

    @Override
    public void run() {

        synchronized (CompareSet.class) {
            CompareSet.count++;
            System.out.println(CompareSet.count);
            if (CompareSet.count == 1000) {
                try {
                    CompareSet.preinitializationComplete.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //只执行一次
            if (CompareSet.preinitializationStarted.compareAndSet(false, true)) {
                System.out.println("11111");
            }
        }
    }

}
